package com.sq.partner.manager.util;

import java.awt.BasicStroke;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.sq.partner.manager.mybatis.model.LogoConfig;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

public final class QRcodeUtil {
    private static Logger logger = LogUtil.getLog(QRcodeUtil.class);
    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    private QRcodeUtil() {
    }

    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }

    public static void writeToFile(BitMatrix matrix, String format, File file)
            throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format "
                    + format + " to " + file);
        }
    }

    public static void writeToStream(BitMatrix matrix, String format,
            OutputStream stream) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, stream)) {
            throw new IOException("Could not write an image of format "
                    + format);
        }
    }
    public static void writeToStream1(BitMatrix matrix, String format,
    		OutputStream stream,String url) throws IOException {
    	BufferedImage image = toBufferedImage(matrix);
    	addLogo_QRCode(image, new File(url), new LogoConfig());
    	if (!ImageIO.write(image, format, stream)) {
    		throw new IOException("Could not write an image of format "
    				+ format);
    	}
    }

    /**
     * @param response
     *            HttpServletResponse
     * @param text
     *            需要转换成二维码的内容,不可为空
     * @param picFormat
     *            指定图片格式 gif、png等，可为空
     * @param picName
     *            指定图片名称，可为空
     * @param width
     *            图片的宽度，可为空,缺省值300
     * @param height
     *            图片的高度，可为空,缺省值300
     * */
    public static void QRcodeToStream(HttpServletResponse response,
            String text, String picFormat, String picName, Integer width,
            Integer height) throws Exception {
        if (StrUtil.isEmpty(text)) {
            text = "地址错误";
        }
        if (text.length() > 1000) {
            throw new Exception("生成二维码内容不宜过长!");
        }
        if (StrUtil.isEmpty(picFormat)) {
            picFormat = "gif";
        }
        if (StrUtil.isEmpty(picName)) {
            picName = "QRcode";
        }
        if (width == null || width < 0 || width > 300) {
            width = 300;
        }
        if (height == null || height < 0 || height > 300) {
            height = 300;
        }
        // 二维码的图片格式
        try {
            OutputStream os = response.getOutputStream();
            BitMatrix bitMatrix = new MultiFormatWriter().encode(text,
                    BarcodeFormat.QR_CODE, width, height);
            response.addHeader("Content-disposition", "attachment; filename="
                    + new String(picName.getBytes("utf-8"), "ISO8859-1") + "."
                    + picFormat);
            response.setContentType("application/octet-stream");
            QRcodeUtil.writeToStream(bitMatrix, picFormat, os);
        } catch (WriterException e) {
            // TODO Auto-generated catch block
            logger.info(e);
        }

    }
    /**
     * @param response
     *            HttpServletResponse
     * @param text
     *            需要转换成二维码的内容,不可为空
     * @param picFormat
     *            指定图片格式 gif、png等，可为空
     * @param picName
     *            指定图片名称，可为空
     * @param width
     *            图片的宽度，可为空,缺省值300
     * @param height
     *            图片的高度，可为空,缺省值300
     * */
    public static void QRcodeToStream1(HttpServletResponse response,
    		String text, String picFormat, String picName, Integer width,
    		Integer height,String url) throws Exception {
    	if (StrUtil.isEmpty(text)) {
    		text = "地址错误";
    	}
    	if (text.length() > 1000) {
    		throw new Exception("生成二维码内容不宜过长!");
    	}
    	if (StrUtil.isEmpty(picFormat)) {
    		picFormat = "gif";
    	}
    	if (StrUtil.isEmpty(picName)) {
    		picName = "QRcode";
    	}
    	if (width == null || width < 0 || width > 300) {
    		width = 300;
    	}
    	if (height == null || height < 0 || height > 300) {
    		height = 300;
    	}
    	// 二维码的图片格式
    	try {
    		OutputStream os = response.getOutputStream();
    		BitMatrix bitMatrix = new MultiFormatWriter().encode(text,
    				BarcodeFormat.QR_CODE, width, height);
    		response.addHeader("Content-disposition", "attachment; filename="
    				+ new String(picName.getBytes("utf-8"), "ISO8859-1") + "."
    				+ picFormat);
    		response.setContentType("application/octet-stream");
    		QRcodeUtil.writeToStream1(bitMatrix, picFormat, os,url);
    	} catch (WriterException e) {
    		// TODO Auto-generated catch block
    		logger.info(e);
    	}
    	
    }
    
    public static BufferedImage addLogo_QRCode(BufferedImage barCodeImage, File logoPic, LogoConfig logoConfig) {
        try {
            if (!logoPic.isFile()) {
                System.out.print("file not find !");
                throw new IOException("file not find !");
            }

            /**
             * 读取二维码图片，并构建绘图对象
             */
            Graphics2D g = barCodeImage.createGraphics();

            /**
             * 读取Logo图片
             */
            BufferedImage logo = ImageIO.read(logoPic);

            int widthLogo = barCodeImage.getWidth() / logoConfig.getLogoPart();
            int heightLogo = barCodeImage.getWidth() / (logoConfig.getLogoPart()+2); //保持二维码是正方形的

            // 计算图片放置位置
            int x = (barCodeImage.getWidth() - widthLogo) / 2;
            int y = (barCodeImage.getHeight() - heightLogo) / 2;


            //开始绘制图片
            g.drawImage(logo, x, y, widthLogo, heightLogo, null);
            g.drawRoundRect(x, y, widthLogo, heightLogo, 10, 10);
            g.setStroke(new BasicStroke(logoConfig.getBorder()));
            g.setColor(logoConfig.getBorderColor());
            g.drawRect(x, y, widthLogo, heightLogo);

            g.dispose();
            return barCodeImage;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
	   * 二维码生成实例
	   * */
	/*   public static void main(String args[]){//core.2.3.0.jar 依赖谷歌的jar包2.x.x大版本支持jdk1.6,3.x.x版本要jdk1.7以上
		   String text = "http://www.hao123.com"; 
	        int width = 300; 
	        int height = 300; 
	        //二维码的图片格式 
	        String format = "gif"; 
	        Hashtable hints = new Hashtable(); 
	        //内容所使用编码 
	        hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); 
	        BitMatrix bitMatrix;
			try {
				bitMatrix = new MultiFormatWriter().encode(text,BarcodeFormat.QR_CODE, width, height, hints);
				 //生成二维码 
		        File outputFile = new File("e:"+File.separator+"new.gif"); 
		        QRcodeUtil.writeToFile(bitMatrix, format, outputFile);//生成文件到本地磁盘 
//		        QRcodeUtil.writeToStream(bitMatrix, format, stream);//生成流
//		        QRcodeUtil.QRcodeToStream(response, text, picFormat, picName, width, height);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	       
	   }*/
}
